import requests
import json
import time
from datetime import datetime


def calculate_loss(base_url="http://119.91.232.205:6666", auth_token=None, loss_calc_payload=None, transactions=None):
    """
    股票盈亏试算完整业务流程
    """
    headers = {
        'platform': 'ios',
        'appversion': '1.0.0',
        'language': 'zh-CN',
        'Content-Type': 'application/json'
    }

    results = {}

    # 用户登录，获取认证token
    if not auth_token:
        login_url = f"{base_url}/v1/user/login"
        login_payload = {
            "email": "test@test.com",
            "password": "Aa123456",
            "keep": True
        }
        response = requests.post(login_url, headers=headers, json=login_payload)
        results['login'] = response.json()
        auth_token = response.json().get('data').get('token')

    headers['Authorization'] = f'Bearer {auth_token}'

    # 创建股票试算记录
    loss_calc_url = f"{base_url}/v1/loss_caculation/add_update"
    response = requests.post(loss_calc_url, headers=headers, json=loss_calc_payload)
    results['loss_calculation'] = response.json()

    # 获取试算记录ID
    loss_id = results['loss_calculation'].get('data', {}).get('id')

    # 提交股票交易记录
    detail_url = f"{base_url}/v1/loss_caculation_detail/add_update"

    results['loss_details'] = []

    for transaction in transactions:
        detail_payload = {
            "lossId": loss_id,  # 试算记录ID
            "operationTime": int(time.mktime(datetime.strptime(transaction['operationTime'], "%Y-%m-%d").timetuple())),
            "direction": 1 if transaction['direction'] == 'buy' else 0,  # 交易方向：0-卖出，1-买入
            "price": transaction['price'],
            "qty": transaction['qty'],
            "amount": transaction['amount']
        }
        response = requests.post(detail_url, headers=headers, json=detail_payload)
        results['loss_details'].append(response.json())
    print("所有交易记录提交完成")

    # 执行盈亏试算
    calculate_url = f"{base_url}/v1/loss_caculation/begin_caculat"
    params = {'caculateId': loss_id}  # 试算记录ID
    response = requests.get(calculate_url, headers=headers, params=params)
    results['calculation_result'] = response.json()
    return results


# 使用示例
if __name__ == "__main__":
    try:
        loss_calc_payload = {
            "stockNo": "600543",  # 股票代码
            "stockName": "莫高股份",  # 股票名称
            "brokerName": "中信证券",  # 券商名称
            "stockBroker": "600030"  # 券商代码
        }

        transactions = [
            {
                "stockNo": "600543",
                "operationTime": "2022-05-16",
                "direction": "buy",
                "price": 9.80,
                "qty": 2800,
                "amount": 27440
            },
            {
                "stockNo": "600543",
                "operationTime": "2022-05-20",
                "direction": "buy",
                "price": 9.50,
                "qty": 1200,
                "amount": 11400
            },
            {
                "stockNo": "600543",
                "operationTime": "2022-05-22",
                "direction": "sell",
                "price": 10.00,
                "qty": 1500,
                "amount": 15000
            },
            {
                "stockNo": "600543",
                "operationTime": "2022-05-31",
                "direction": "buy",
                "price": 9.20,
                "qty": 500,
                "amount": 4600
            },
            {
                "stockNo": "600543",
                "operationTime": "2022-06-15",
                "direction": "sell",
                "price": 7.00,
                "qty": 2000,
                "amount": 14000
            }
        ]

        results = calculate_loss(loss_calc_payload=loss_calc_payload, transactions=transactions)
        print("盈亏试算流程完成，结果：")
        for step, result in results.items():
            print(f"\n{step}:", json.dumps(result, indent=2, ensure_ascii=False))
    except Exception as e:
        print(f"执行过程中出现错误: {str(e)}")

"""
# FIXME 测试成功？损失金额四舍五入保留小数点后3位
测算结果：status=10 成功，预期损失金额=8652.4999 实际损失金额estimate_loss_ammount=8652.500

SELECT * from stock_loss_caculation where id=885422220216635392;
SELECT * from stock_loss_caculation_detail where loss_id = 885422220216635392;
"""
